//
//  HBHMainSearchViewController.m
//  HubeiHotel
//
//  Created by 张露杰 on 17/11/16.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "HBHMainSearchViewController.h"
#import "DetailJiuDianViewController.h"

#import "HBHMainSearchHistoryCell.h"
#import "HBHMainResumeCell.h"
#import "HBHMainBusinessCell.h"
#import "JiuDianCell.h"
#import "HBHChouseTypeView.h"
typedef enum : NSUInteger {
    HBHMainSearchingState = 0, //搜索中
    HBHMainUnSearchState, //未搜索
} HBHMainSearchState;

@interface HBHMainSearchViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,BMKLocationServiceDelegate>
{
    HBHMainSearchState _state;
    NSMutableArray *_titles;
}

@property (nonatomic, strong) UITableView *table;

@property (nonatomic, retain) NSMutableArray *datas;
@property (nonatomic, copy) NSString *keyWord;

/**
 定位类
 */
@property (nonatomic, strong) BMKLocationService *locService;

/**
 用户位置
 */
@property (nonatomic, strong) BMKUserLocation *userLocation;

@end

@implementation HBHMainSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initSearchBarWithPlaceholder:@"请输入关键字搜索" showsCancelButton:YES];
    [self creatView];
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    [self.locService startUserLocationService];
}

-(void)creatView
{
    _titles = @[@"全部",@"附近",@"智能排序"].mutableCopy;
    _datas = [NSMutableArray new];
    _keyWord = @"";
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame = CGRectMake(0, 0, 20*screenW_6, 15*screenW_6);
//    [btn addTarget:self action:@selector(onTapLeftBarButton) forControlEvents:UIControlEventTouchUpInside];
//    [btn addSubview:[TomamaUI createImageView:CGRectMake(0, 0, 9*screenW_6, 15*screenW_6) backGroundImageV:@"back"]];
//    UIBarButtonItem *barButtonitem = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    self.navigationItem.leftBarButtonItem = barButtonitem;
    _state = HBHMainUnSearchState;
    [self.view addSubview:self.table];
}

-(UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - 64) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsHorizontalScrollIndicator = NO;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle = 0;
        _table.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _table.backgroundColor = [UIColor clearColor];
    }
    return _table;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_state == HBHMainUnSearchState) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 42*screenW_6)];
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [TomamaUI createLabel:CGRectMake(12*screenW_6, 14*screenW_6, 100*screenW_6, 14*screenW_6) textAligment:0 font:[UIFont systemFontOfSize:14*screenW_6] textColor:TextBlack text:@"历史记录"];
        [view addSubview:label];
        
        UIButton *btn = [TomamaUI createButton:0 Frame:CGRectMake(SCREENW - 44*screenW_6, 0, 42*screenW_6, 42*screenW_6) targ:self sel:@selector(deleteHistory) titleColor:nil font:nil title:nil image:@"Main_search_delete" backGroundImage:nil];
        [view addSubview:btn];
        
        return view;
    }else if (_state == HBHMainSearchingState){
//        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 41*screenW_6)];
//        view.backgroundColor = [UIColor whiteColor];
//        for (int i = 0; i < _titles.count; i++) {
//            HBHChouseTypeView *typeView = [[HBHChouseTypeView alloc]initWithFrame:CGRectMake(i*SCREENW/3, 0, 0, 0) title:_titles[i] complete:^(NSString *title) {
//                
//            }];
//            [view addSubview:typeView];
//            if (i < 2) {
//                UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(typeView.frame) - .5, 0, 1, 14*screenW_6)];
//                lineView.backgroundColor = backColor;
//                [view addSubview:lineView];
//                lineView.center = CGPointMake(lineView.center.x, view.frame.size.height/2);
//            }
//        }
//        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 41*screenW_6 - .5, SCREENW, .5)];
//        lineView.backgroundColor = backColor;
//        [view addSubview:lineView];
//        return view;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_state == HBHMainSearchingState) {
        return .1*screenW_6;
    }
    return 42*screenW_6;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_state == HBHMainUnSearchState) {
        return 1;
    }
    return _datas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    if (_state == HBHMainUnSearchState) {
        HBHMainSearchHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HBHMainSearchHistoryCell"];
        if (!cell) {
            cell = [[HBHMainSearchHistoryCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HBHMainSearchHistoryCell"];
        }
        [cell loadCellWithComplete:^(NSString *text) {
            weakSelf.keyWord = text;
            [weakSelf searchRequest];
        }];
        return cell;
    }else if (_state == HBHMainSearchingState){
        JiuDianCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JiuDianCell"];
        if (!cell) {
            cell = [[JiuDianCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"JiuDianCell"];
        }
        [cell loadCellWithData:_datas[indexPath.row]];
        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_state == HBHMainUnSearchState) {
        NSArray *array = [standfault objectForKey:@"searchHistory"];
        if (array.count == 0) {
            return 60*screenW_6;
        }else{
            UIView *lastView;
            NSInteger lineNum = 1;
            for (int i = 0; i < array.count; i++) {
                UILabel *label;
                if (i == 0) {
                    label = [TomamaUI createLabel:CGRectMake(12*screenW_6, 0, [TomamaUI getStringWeithtWith:array[i] andHeigth:32*screenW_6 andFont:[UIFont systemFontOfSize:13*screenW_6]], 32*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:13*screenW_6] textColor:TextBlack text:array[i]];
                }else{
                    label = [TomamaUI createLabel:CGRectMake(CGRectGetMaxX(lastView.frame) + 10*screenW_6, lastView.frame.origin.y, [TomamaUI getStringWeithtWith:array[i] andHeigth:32*screenW_6 andFont:[UIFont systemFontOfSize:13*screenW_6]] + 30*screenW_6, 32*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:13*screenW_6] textColor:TextBlack text:array[i]];
                    if (CGRectGetMaxX(label.frame) > SCREENW - 12*screenW_6) {
                        label.frame = CGRectMake(12*screenW_6, CGRectGetMaxY(lastView.frame) + 9*screenW_6, label.frame.size.width, label.frame.size.height);
                        lineNum ++;
                    }
                }
                lastView = label;
            }
            return 41*screenW_6*lineNum;
        }
    }else if (_state == HBHMainSearchingState){
        return 150*screenW_6;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_state == HBHMainSearchingState) {//跳转酒店详情
        if (indexPath.row >= _datas.count) {
            return;
        }
        if (![Storage isLogin]) {
            [Storage goToLogin];
        }else{
            DetailJiuDianViewController *vc = [DetailJiuDianViewController new];
            vc.hotelId = _datas[indexPath.row][@"id"];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (![TomamaUI isNotNullStr:[[searchBar.text componentsSeparatedByString:@" "] componentsJoinedByString:@""]]) {
        _state = HBHMainUnSearchState;
        [_table reloadData];
        return;
    }
    NSMutableArray *array = [NSMutableArray arrayWithArray:[standfault objectForKey:@"searchHistory"]];
    if (!array) {
        array = [NSMutableArray array];
    }
    if (![array containsObject:searchBar.text]) {
        [array addObject:searchBar.text];
        [standfault setObject:array forKey:@"searchHistory"];
        [standfault synchronize];
    }
    [searchBar resignFirstResponder];
    
    [self.view endEditing:YES];
    
    [_datas removeAllObjects];
    [self searchRequest];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    HBHBackView *view;
    if ([self.view viewWithTag:100]) {
        view = (id)[self.view viewWithTag:100];
    }else{
        view = [[HBHBackView alloc] init];
        view.tag = 100;
    }
    view.blcok = ^(){
        [searchBar resignFirstResponder];
    };
    [self.view addSubview:view];
    return YES;
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    UIView *view = [self.view viewWithTag:100];
    [view removeFromSuperview];
    _keyWord = searchBar.text;
    return YES;
}

#pragma mark - @selector
-(void)deleteHistory
{
    [standfault removeObjectForKey:@"searchHistory"];
    [_table reloadData];
}

-(void)searchRequest
{
    if (!_userLocation) {
        UIAlertController*alertController = [UIAlertController alertControllerWithTitle:@"未获取到用户位置" message:@"是否重新定位" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*_Nonnullaction) {
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
            [HudHelper showProgressHudWithMessage:@"" toView:self.view];
            [self.locService startUserLocationService];
        }]];
        [self presentViewController:alertController animated:YES completion:^{
        }];
        return;
    }
    _state = HBHMainSearchingState;
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/business/businessBeanList" Dic:@{@"name":_keyWord,@"longitude":[NSString stringWithFormat:@"%lf",_userLocation.location.coordinate.longitude],@"latitude":[NSString stringWithFormat:@"%lf",_userLocation.location.coordinate.latitude],@"city.id":[standfault objectForKey:@"cityID"]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {
                    if (_datas.count < [responseDic[@"count"] integerValue]) {
                        [_datas addObjectsFromArray:responseDic[@"data"]];
                        if (_datas.count == 0) {
                            [TomamaUI creatAlertWithTarget:self message:@"未搜索到相关酒店" timeInterval:2];
                        }
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
                [_table reloadData];
                if ([_table.mj_header isRefreshing]) {
                    [_table.mj_header endRefreshing];
                }
                if ([_table.mj_footer isRefreshing]) {
                    if (_datas.count < [responseDic[@"count"] integerValue]) {
                        [_table.mj_footer endRefreshing];
                    }else{
                        [_table.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            });
        }];
    });
}


#pragma mark - BMKLocationService
-(BMKLocationService *)locService
{
    if (!_locService) {
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
    }
    return _locService;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _userLocation = userLocation;
    if (_userLocation) {
        [HudHelper hideHudToView:self.view];
        [self.locService stopUserLocationService];
    }
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    [HudHelper hideHudToView:self.view];
}

@end
